<template>
  <div class="content">
    <el-form style="width:70%" label-width="80px" :model="user" :rules="userRule" ref="userForm">
      <el-form-item label="用户名">{{ user.username }}</el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="user.realName" :disabled="update"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobilePhone">
        <el-input v-model="user.mobilePhone" :disabled="update"/>
      </el-form-item>
      <el-form-item>
        <el-button v-show="!update" @click="handlerUpdate" :loading="submitLoading">完成</el-button>
        <el-button @click="update=!update">{{ update?"修改":"返回" }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {isMobile} from "../../utils/validate";
  import API from '@/api'

  export default {
    name: "index",
    data(){
      let validatePhone = (rule,value,callback)=>{
        if (!isMobile(value)){
          callback(new Error('手机号格式错误'));
        }else {
          callback();
        }
      };
      return{
        update:true,
        user:{
          username:"",
          realName:"",
          mobilePhone:""
        },
        userRule:{
          mobilePhone:[
            {validator:validatePhone,trigger:'blur'}
          ]
        },
        submitLoading:false,
      }
    },
    methods:{
      handlerUpdate(){
          this.$refs['userForm'].validate((valid)=>{
            if (valid){
              this.submitLoading = true;
              API.user.modify(this.user).then((res)=>{
                if(!res.data.code){
                  this.$message({
                    message:"修改成功",
                    type:"success"
                  });
                  this.update = true;
                }else {
                  this.$message.error(res.data.msg);
                }
                this.submitLoading = false;
              }).catch((error)=>{
                this.$message.error("修改失败，请重试");
                this.submitLoading = false;
              })
            }
          });
      }
    },
    activated(){
      API.user.info().then((res)=>{
        this.user = res.data.user;
      }).catch((error)=>{
        this.$message.error("获取用户信息失败，请刷新或退出重试");
      })
    }
  }
</script>

<style scoped>
  .content{
    text-align: center;
    margin:10% 25%;
  }
</style>
